package com.xoa.dev.workFlow.controller;

import com.xoa.dao.WFE.WFEFlowTypeModelMapper;
import com.xoa.dao.WFE.WFEFormTypeMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowFormType;
import com.xoa.model.workflow.FlowTypeModel;
import com.xoa.util.AjaxJson;
import com.xoa.util.CookiesUtil;
import com.xoa.util.HtmlUtil;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/workFlowCreater")
public class WorkFlowCreateController {

    @Autowired
    WFEFormTypeMapper wfeFormTypeMapper;

    @Autowired
    WorkMapper workMapper;

    @Autowired
    WFEFlowTypeModelMapper wfeFlowTypeModelMapper;

    @RequestMapping("/saveFlowAutoNum")
    @ResponseBody
    public AjaxJson saveFlowAutoNum(Integer flowId, Integer runId, String runName,
                                    String beginTime, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        AjaxJson ajaxJson = new AjaxJson();
        String sqlType = "xoa"+(String) request.getSession().getAttribute(
                "loginDateSouse");
        try {
            //获取当前库名，如果为空判断是xoa1000还是xoa1001
            if (StringUtils.checkNull((String) request.getSession().getAttribute(
                    "loginDateSouse"))) {
                sqlType = this.getSqlType();
            }
            String tableName = "flow_data_" + flowId;
            //获取该表数据库中的所有的列
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("tableName", tableName);
            param.put("tableSchema", sqlType);

            //根据flowId获取表单信息，然后获取表单上所有name属性生成flow_data_flowid表
            List<FlowFormType> forms = wfeFormTypeMapper.getFrombyFlowId(flowId);
            FlowFormType formType = forms.get(0);
            //获取表单信息
            Document document = HtmlUtil.getDom(formType.getPrintModel());
            List<String> list = HtmlUtil.getAllData(document);

            //获取该表所有的列
            List<String> columns = workMapper.showColumns(param);
            //没有表则新建
            if (columns.size() == 0) {

                param.put("keys", list);
                //读取配置文件
                ResourceBundle rb = ResourceBundle.getBundle("jdbc-sql");
                String databaseId = rb.getString("driverClassName");
                if (databaseId.contains("oracle")) {
                    workMapper.createSequence(param);
                }
                workMapper.createTable(param);
            }
            Integer flowAutoNum = null;
            //查询该表单的信息
            param.put("runId",runId);
            Map<String, Object> m = workMapper.select(param);
            if (m == null || m.size() == 0) {
                List<Object> key = new ArrayList<Object>();
                List<Object> value = new ArrayList<Object>();
                key.add("RUN_ID");
                value.add(String.valueOf(runId));
                key.add("RUN_NAME");
                value.add(runName);
                key.add("BEGIN_TIME");
                value.add(beginTime);
                key.add("BEGIN_USER");
                value.add(user.getUserId());

                FlowTypeModel flowTypeModel = wfeFlowTypeModelMapper.queryOneObject(flowId);
                if (flowTypeModel.getAutoNum() != null && flowTypeModel.getAutoNum() != 0) {
                    flowAutoNum = flowTypeModel.getAutoNum() + 1;
                    key.add("FLOW_AUTO_NUM");
                    value.add(flowAutoNum);
                }

                for (String temp : list) {
                    key.add(temp);
                    value.add("");
                }
                param.put("keys", key);
                param.put("values", value);
                workMapper.insert(param);
            }else{
                flowAutoNum = Integer.parseInt(m.get("flow_auto_num").toString());
            }
            ajaxJson.setFlag(true);
            ajaxJson.setMsg("OK");
            ajaxJson.setObj(flowAutoNum);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
        }
        return ajaxJson;
    }

    //获取默认库名
    public String getSqlType() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tableSchema", "xoa1000");
        map.put("tableName", "user");
        List<String> list = workMapper.showColumns(map);
        String sqlType = "xoa1000";
        if (list.size() == 0) {
            sqlType = "xoa1001";
        }
        return sqlType;
    }
}
